<template>
  <!--  PullRefresh 组件 结合list组件事件下拉刷新 -->
  <div class="scroll-wrapper" ref="scrollDiv" @scroll="rememberPosition">
    <!-- 列表组件 -->
    <van-pull-refresh
      loosing-text="给爷松开!刷新~~"
      pulling-text="赶紧往下的拉!"
      loading-text="哥哥,正在加载数据哦,可别着急呢"
      success-text="刷新成功,数据已经重新加载"
      head-height="100"
      success-duration="500"
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="底部已经没有数据啦!"
        @load="onLoad"
      >
        <van-cell
          :to="`/article/${item.art_id.toString()}`"
          v-for="(item, ind) in list"
          :key="ind"
        >
          <!--单行数据 -->
          <div class="article_item">
            <h3 class="van-ellipsis">
              {{ item.title }}
            </h3>
            <div class="img_box" v-if="item.cover.type">
              <van-image
                v-for="(image, index) in item.cover.images"
                :key="index"
                lazy-load
                :class="item.cover.type === 1 ? 'w100' : 'w30'"
                fit="cover"
                :src="image"
              >
                <!-- loading懒加载提示插槽 -->
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
                <!-- 加载失败插槽 -->
                <template v-slot:error>加载失败</template>
              </van-image>
            </div>
            <div class="info_box">
              <span>作者: {{ item.aut_name }}</span>
              <span>{{ item.comm_count }}评论</span>
              <span>{{ item.pubdate | relaTime }}</span>
              <span
                v-if="$store.state.user.token"
                class="close"
                @click="openPopup(item.art_id)"
                ><van-icon name="cross"></van-icon
              ></span>
            </div>
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <!-- 弹出层放在根元素结束之前 -->
    <!-- v-model语法糖 === :value + @input -->
    <!-- <MoreAction v-model="isShow"></MoreAction> -->
    <MoreAction
      :value="isShow"
      :artId="artId"
      @input="handlePopup"
      @delAriticleById="delAriticleById"
    ></MoreAction>
  </div>
</template>

<script>
import { getArticleListApi } from '@/api/homeAPI.js'
import MoreAction from './more-action.vue'
export default {
  components: {
    MoreAction
  },
  data () {
    return {
      isShow: false,
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      // 当前时间戳
      timestamp: Date.now(),
      // 记录文章列表滚动的距离
      scrollTop: 0,
      artId: 0
    }
  },
  props: {
    channel_id: {
      type: [Number, String],
      default: 1
    }
  },
  methods: {
    // 通过文章id删除文章
    delAriticleById (articleid) {
      const index = this.list.findIndex((item) => item.art_id === articleid)
      console.log('找到文章id对应的数据', index)
      // 根据索引删除
      this.list.splice(index, 1)
    },
    handlePopup (closePopup) {
      console.log('Popup组件子传给父的参数', closePopup)
      this.isShow = closePopup // 语法糖v-model 会内部给你改!
    },
    rememberPosition (event) {
      this.scrollTop = event.target.scrollTop
    },
    openPopup (artId) {
      // 打开Popup弹出层
      this.isShow = true
      // 把传过来的参数传给MoreAction组件props
      this.artId = artId
    },
    // 滚动到上次页面滚动到的位置===>放入缓存中执行
    scrollPosition () {
      // 拿到DOM元素===>更新DOM是异步的
      this.$nextTick(() => {
        this.$refs.scrollDiv.scrollTop = this.scrollTop
      })
    },
    async onLoad () {
      // console.log('组件实例', this)
      await this.$sleep(2000) // 睡线程
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // console.log('已经下拉开始加载', this.loading)
      const { data } = await getArticleListApi(this.channel_id, this.timestamp)
      console.log('文章列表请求api', data)
      // 给list追加数据
      this.list.push(...data.results)
      // 加载状态的结束(转圈圈完毕)
      this.loading = false
      // 刷新状态的结束
      this.refreshing = false

      // 数据全部加载完成 ===>判断时间戳是否为null
      if (!data.pre_timestamp) {
        this.finished = true
      } else {
        // 如果请求返回的时间戳还有数据 就把查询下一页数据的时间戳给请求参数timestamp
        this.timestamp = data.pre_timestamp
      }
    },
    onRefresh () {
      // 清空列表数据
      if (this.refreshing) {
        this.list = []
      }
      // 清空列表数据
      this.finished = false

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true // 刷新时手动开启加载效果(因为没有上拉加载)
      // 刷新需要重置时间戳===>改为当前时间戳
      this.timestamp = Date.now()
      this.onLoad()
    }
  },
  activated () {
    // console.log('ArticleList子子组件也缓存到了keep-alive中 并且已经激活了')
    // 滚动到上次失活之前滚动到的距离
    this.scrollPosition()
  },
  deactivated () {
    // console.log('ArticleList子子组件先在内存中失活了')
  }
}
</script>

<style lang="less" scoped>
// 一条新闻的结构样式
.article_item {
  h3 {
    font-weight: normal;
    line-height: 2;
  }
  .img_box {
    display: flex;
    justify-content: space-between;
    .w33 {
      width: 33%;
      height: 90px;
    }
    .w100 {
      width: 100%;
      height: 180px;
    }
  }
  .info_box {
    color: #999;
    line-height: 2;
    position: relative;
    font-size: 12px;
    span {
      padding-right: 10px;
      &.close {
        border: 1px solid #ddd;
        border-radius: 2px;
        line-height: 15px;
        height: 12px;
        width: 16px;
        text-align: center;
        padding-right: 0;
        font-size: 8px;
        position: absolute;
        right: 0;
        top: 7px;
      }
    }
  }
}
</style>
